﻿using System;
using System.Windows.Forms;

namespace BS.FormControls
{
    public class NumericComboBox : ComboBox
    {
        private bool nonDigit = false;

        public int Number
        {
            get
            {
                if (String.IsNullOrEmpty(base.Text))
                    return this.SelectedNumber;
                else
                    return int.Parse(base.Text);
            }
        }

        private int SelectedNumber
        {
            get
            {
                int value = 0;
                int.TryParse(this.SelectedItem as string, out value);
                return value;
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            nonDigit = !IsKeyStrokeNumber(e.KeyCode);
            base.OnKeyDown(e);
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            e.Handled = nonDigit;
            base.OnKeyPress(e);
        }

        private bool IsKeyStrokeNumber(Keys key)
        {
            return
                ((Control.ModifierKeys != (Keys.Control | Keys.Alt)) &&
                (Control.ModifierKeys != Keys.Shift)) &&
                (key >= Keys.D0 && key <= Keys.D9) ||
                (key >= Keys.NumPad0 && key <= Keys.NumPad9) ||
                (key == Keys.Back);
        }
    }
}
